

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="ShanCe">
  <meta name="keywords" content="">
  
    <meta name="description" content="文档地址：https:&#x2F;&#x2F;docs.celeryq.dev&#x2F;en&#x2F;v5.2.3&#x2F;index.html 项目构建1.环境安装1234pip install celery&#x3D;&#x3D;5.1.2pip install redis&#x3D;&#x3D;4.3.5pip install django-celery-beat&#x3D;&#x3D;2.2.0pip install django-celery-results&#x3D;&#x3D;2.0.1  django-">
<meta property="og:type" content="article">
<meta property="og:title" content="1.celery-django环境搭建">
<meta property="og:url" content="https://sweetshance.github.io/2024/06/17/celery+django%E6%90%AD%E5%BB%BA%E5%AD%A6%E4%B9%A0/1-celery-django%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA/index.html">
<meta property="og:site_name" content="ShanCe的博客">
<meta property="og:description" content="文档地址：https:&#x2F;&#x2F;docs.celeryq.dev&#x2F;en&#x2F;v5.2.3&#x2F;index.html 项目构建1.环境安装1234pip install celery&#x3D;&#x3D;5.1.2pip install redis&#x3D;&#x3D;4.3.5pip install django-celery-beat&#x3D;&#x3D;2.2.0pip install django-celery-results&#x3D;&#x3D;2.0.1  django-">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://sweetshance.github.io/2024/06/17/images/celery/%E7%9B%AE%E5%BD%95.png">
<meta property="article:published_time" content="2024-06-17T09:38:42.000Z">
<meta property="article:modified_time" content="2024-06-18T07:44:32.291Z">
<meta property="article:author" content="ShanCe">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://sweetshance.github.io/2024/06/17/images/celery/%E7%9B%AE%E5%BD%95.png">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>1.celery-django环境搭建 - ShanCe的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"sweetshance.github.io","root":"/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>ShanCe</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="1.celery-django环境搭建"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        ShanCe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2024-06-17 17:38" pubdate>
          2024年6月17日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4.6k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          38 分钟
        
      </span>
    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">1.celery-django环境搭建</h1>
            
            
              <div class="markdown-body">
                
                <p>文档地址：<a target="_blank" rel="noopener" href="https://docs.celeryq.dev/en/v5.2.3/index.html">https://docs.celeryq.dev/en/v5.2.3/index.html</a></p>
<h2 id="项目构建"><a href="#项目构建" class="headerlink" title="项目构建"></a>项目构建</h2><h3 id="1-环境安装"><a href="#1-环境安装" class="headerlink" title="1.环境安装"></a>1.环境安装</h3><figure class="highlight apache"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs apache"><span class="hljs-attribute">pip</span> install celery==<span class="hljs-number">5</span>.<span class="hljs-number">1</span>.<span class="hljs-number">2</span><br><span class="hljs-attribute">pip</span> install redis==<span class="hljs-number">4</span>.<span class="hljs-number">3</span>.<span class="hljs-number">5</span><br><span class="hljs-attribute">pip</span> install django-celery-beat==<span class="hljs-number">2</span>.<span class="hljs-number">2</span>.<span class="hljs-number">0</span><br><span class="hljs-attribute">pip</span> install django-celery-results==<span class="hljs-number">2</span>.<span class="hljs-number">0</span>.<span class="hljs-number">1</span><br></code></pre></td></tr></table></figure>
<blockquote>
<p>django-celery-beat 是对celery定时任务的管理（继承admin后台）<br>django-celery-results 是对celery worker执行结果的管理（继承admin后台）</p>
</blockquote>
<h3 id="2-目录结构"><a href="#2-目录结构" class="headerlink" title="2.目录结构"></a>2.目录结构</h3><!-- ![目录结构](/images/celery/目录.png) -->
<p><img src="../../images/celery/%E7%9B%AE%E5%BD%95.png" srcset="/img/loading.gif" lazyload alt="目录结构"></p>
<ol>
<li>celeryAbout 是我的项目</li>
<li>celeryd是我创建的一个app</li>
</ol>
<h3 id="3-注册app"><a href="#3-注册app" class="headerlink" title="3.注册app"></a>3.注册app</h3><p>在celeryAbout/settings.py中的INSTALLED_APPS中增加</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs ini"><span class="hljs-attr">INSTALLED_APPS</span> = [<br>    ....   <br>    <span class="hljs-string">&#x27;django_celery_beat&#x27;</span>,<br>    <span class="hljs-string">&#x27;django_celery_results&#x27;</span>,<br>]<br></code></pre></td></tr></table></figure>

<h3 id="4-celery配置"><a href="#4-celery配置" class="headerlink" title="4.celery配置"></a>4.celery配置</h3><blockquote>
<p>celery的配置可以写在setting.py 里也可以写在自己单独的配置文件中，在注册配置文件注册不同的地址就行</p>
</blockquote>
<ol>
<li>新建配置文件，目录: celeryd/config.py (名字不固定)<br>配置内容<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> celery.schedules <span class="hljs-keyword">import</span> crontab<br><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> timedelta<br><br><br><span class="hljs-comment">########### celery #############</span><br><span class="hljs-comment"># 设置代理人</span><br>broker_url = <span class="hljs-string">&quot;redis://127.0.0.1:6379/11&quot;</span><br><span class="hljs-comment"># 使用django orm 作为结果存储</span><br>result_backend = <span class="hljs-string">&#x27;django-db&#x27;</span><br><span class="hljs-comment"># result_backend = &#x27;redis://127.0.0.1:6379/14&#x27;</span><br><span class="hljs-comment"># celery使用的cache(这里对应的是settings里的缓存配置)</span><br>celery_cache_backend = <span class="hljs-string">&#x27;default&#x27;</span><br><span class="hljs-comment"># result_backend = &#x27;redis://localhost/0&#x27;</span><br><span class="hljs-comment"># celery 的启动工作数量设置</span><br>worker_concurrency = <span class="hljs-number">5</span><br><span class="hljs-comment"># 任务预取功能，就是每个工作的进程／线程在获取任务的时候，会尽量多拿 n 个，以保证获取的通讯成本可以压缩。</span><br>worker_prefetch_multiplier = <span class="hljs-number">5</span><br><span class="hljs-comment"># celery 的 worker 执行多少个任务后进行重启操作</span><br>worker_max_tasks_per_child = <span class="hljs-number">100</span><br><span class="hljs-comment"># 禁用所有速度限制，如果网络资源有限，不建议开足马力。</span><br>worker_disable_rate_limits = <span class="hljs-literal">True</span><br><span class="hljs-comment"># 指定任务接受的序列化类型</span><br>accept_content = [<span class="hljs-string">&#x27;json&#x27;</span>]<br><span class="hljs-comment"># 指定任务序列化方式</span><br>task_serializer = <span class="hljs-string">&#x27;json&#x27;</span><br><span class="hljs-comment"># 指定结果序列化的方式</span><br>result_serializer = <span class="hljs-string">&#x27;json&#x27;</span><br><br><span class="hljs-comment"># 时区设置</span><br>timezone = <span class="hljs-string">&#x27;Asia/Shanghai&#x27;</span><br>enable_utc = <span class="hljs-literal">False</span><br>beat_sync_every = <span class="hljs-number">1</span><br><span class="hljs-comment"># settings USE_TZ=False时添加该选项，否启动 django celery beat 的时候，出现这个错误TypeError: can&#x27;t compare offset-naive and offset-aware datetimes</span><br>DJANGO_CELERY_BEAT_TZ_AWARE = <span class="hljs-literal">False</span> <br><span class="hljs-comment"># 休眠最大秒数</span><br>beat_max_loop_interval = <span class="hljs-number">300</span><br>beat_scheduler = <span class="hljs-string">&#x27;django_celery_beat.schedulers:DatabaseScheduler&#x27;</span><br>celery_task_time_limit = <span class="hljs-number">30</span>*<span class="hljs-number">60</span><br><span class="hljs-comment">########### celery #############</span><br><span class="hljs-comment"># 配置定时任务</span><br>beat_schedule = &#123;<br>        <span class="hljs-comment">#定时任务名字</span><br>        <span class="hljs-string">u&#x27;测试定时器1&#x27;</span>: &#123;<br>            <span class="hljs-comment"># 定时任务的方法 test 是函数名 celeryd.tasks是其文件路径，后边会继续介绍</span><br>            <span class="hljs-string">&#x27;task&#x27;</span>: <span class="hljs-string">&#x27;celeryd.tasks.test&#x27;</span>,<br>            <span class="hljs-comment"># 间隔时间</span><br>            <span class="hljs-string">&#x27;schedule&#x27;</span>: timedelta(seconds=<span class="hljs-number">10</span>),<br>            <span class="hljs-string">&#x27;args&#x27;</span>: ()<br>        &#125;<br>    &#125;<br></code></pre></td></tr></table></figure>
注意： </li>
</ol>
<ul>
<li>配置项，因celery版本升级从大写切换为小写详情:<a target="_blank" rel="noopener" href="https://docs.celeryq.dev/en/v5.2.3/userguide/configuration.html">https://docs.celeryq.dev/en/v5.2.3/userguide/configuration.html</a></li>
<li>定时任务时间配置:</li>
</ul>
<ol start="2">
<li>settings 缓存配置<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python">CACHES = &#123;<br>    <span class="hljs-string">&#x27;default&#x27;</span>: &#123;<br>        <span class="hljs-string">&#x27;BACKEND&#x27;</span>: <span class="hljs-string">&#x27;django.core.cache.backends.db.DatabaseCache&#x27;</span>,<br>        <span class="hljs-string">&#x27;LOCATION&#x27;</span>: <span class="hljs-string">&#x27;my_cache_table&#x27;</span>,<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
注意：<br>定时任务的配置:<a target="_blank" rel="noopener" href="https://docs.celeryq.dev/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers">https://docs.celeryq.dev/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers</a></li>
</ol>
<h3 id="5-celery主程序书写"><a href="#5-celery主程序书写" class="headerlink" title="5.celery主程序书写"></a>5.celery主程序书写</h3><p>创建文件，celeryAbout/celeryd.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> __future__ <span class="hljs-keyword">import</span> absolute_import<br><span class="hljs-keyword">import</span> os<br><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery<br><span class="hljs-keyword">from</span> django.conf <span class="hljs-keyword">import</span> settings<br><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> timedelta<br><span class="hljs-comment"># from . import config</span><br><br><span class="hljs-comment"># 为celery设置环境变量</span><br>os.environ.setdefault(<span class="hljs-string">&#x27;DJANGO_SETTINGS_MODULE&#x27;</span>, <span class="hljs-string">&#x27;celeryAbout.settings&#x27;</span>)<br><br>app = Celery(<span class="hljs-string">&#x27;celeryAbout&#x27;</span>)<br><span class="hljs-comment"># 加载配置</span><br><span class="hljs-comment"># app.config_from_envvar(&#x27;DJANGO_SETTINGS_MODULE&#x27;)</span><br><span class="hljs-comment"># (读取配置文件里的配置)</span><br>app.config_from_object(<span class="hljs-string">&quot;celeryd.config&quot;</span>)<br><span class="hljs-comment"># 读取settings里的配置(如果配置在settings.py 文件中的时候),namespace 是只配置项的前缀，可以不写</span><br><span class="hljs-comment"># app.config_from_object(&#x27;django.conf:settings&#x27;, namespace=&#x27;CELERY&#x27;)</span><br><span class="hljs-comment"># 设置app自动加载任务</span><br><span class="hljs-comment"># app.autodiscover_tasks([&#x27;celeryd&#x27;])</span><br><span class="hljs-comment"># 发现任务文件每个app下的task.py （一般celery任务方法都是写在tasks文件中，这样的示例如上一行，具体可以看autodiscover_tasks方法注释很详细 ）这个会将tasks.py里边的方法读取到，可以在dmin后台使用</span><br>app.autodiscover_tasks(<span class="hljs-keyword">lambda</span>: settings.INSTALLED_APPS)<br></code></pre></td></tr></table></figure>

<h3 id="6-在绑定celery"><a href="#6-在绑定celery" class="headerlink" title="6.在绑定celery"></a>6.在绑定celery</h3><p>在celeryAbout/_<em>init</em>_.py中将celery注册到项目中</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> .celeryd <span class="hljs-keyword">import</span> app<br>__all__ = [<span class="hljs-string">&#x27;app&#x27;</span>]<br></code></pre></td></tr></table></figure>

<h3 id="7-在celeryd-tasks-py-中书写任务"><a href="#7-在celeryd-tasks-py-中书写任务" class="headerlink" title="7.在celeryd/tasks.py 中书写任务"></a>7.在celeryd/tasks.py 中书写任务</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> time<br><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> shared_task<br><span class="hljs-keyword">from</span> celeryAbout <span class="hljs-keyword">import</span> app<br><br><span class="hljs-comment"># 这是一个异步任务</span><br><span class="hljs-meta">@shared_task</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">a: <span class="hljs-built_in">int</span>, b: <span class="hljs-built_in">int</span></span>):<br>    <span class="hljs-built_in">print</span>(a + b, <span class="hljs-string">&quot;XXXXXXXXXXXXXXXXX&quot;</span>)<br>    <span class="hljs-keyword">return</span> a + b<br><br><br><span class="hljs-comment"># name可以是定时任务别名，在上边配置定时任务的方法时可以配置别名,例如：</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">beat_schedule = &#123;</span><br><span class="hljs-string">        #定时任务名字</span><br><span class="hljs-string">        u&#x27;测试定时器1&#x27;: &#123;</span><br><span class="hljs-string">            # 定时任务的方法 test 是函数名 celeryd.tasks是其文件路径，后边会继续介绍</span><br><span class="hljs-string">            &#x27;task&#x27;: &#x27;celeryd.test&#x27;,</span><br><span class="hljs-string">            # 间隔时间</span><br><span class="hljs-string">            &#x27;schedule&#x27;: timedelta(seconds=10),</span><br><span class="hljs-string">            &#x27;args&#x27;: ()</span><br><span class="hljs-string">        &#125;</span><br><span class="hljs-string">    &#125;</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-comment"># @shared_task(name=&quot;celeryd.test&quot;)</span><br><span class="hljs-comment"># 这是一个定时任务</span><br><span class="hljs-meta">@app.task</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>():<br>    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">30</span>):<br>        time.sleep(<span class="hljs-number">1</span>)<br>        <span class="hljs-built_in">print</span>(i)<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;task worker ===============&quot;</span>)<br><br></code></pre></td></tr></table></figure>

<h3 id="8-异步任务使用"><a href="#8-异步任务使用" class="headerlink" title="8.异步任务使用"></a>8.异步任务使用</h3><p>在想要异步执行的地方，一般时接口里</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 1. 方法一</span><br>add.delay(<span class="hljs-number">10</span>, <span class="hljs-number">11</span>)<br><span class="hljs-comment"># 2. 方法二 CELERY_DEFAULT_QUEUE 为指定队列</span><br>add.apply_async(args=[<span class="hljs-number">10</span>， <span class="hljs-number">11</span>], queue=CELERY_DEFAULT_QUEUE)<br></code></pre></td></tr></table></figure>

<h3 id="9-启动celery"><a href="#9-启动celery" class="headerlink" title="9.启动celery"></a>9.启动celery</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-comment"># 启动worker</span><br>celery -A celeryAbout worker -l INFO <br><span class="hljs-comment"># 启动beat</span><br>celery -A celeryAbout beat<br></code></pre></td></tr></table></figure>
<p>注意：如果启动worker报错</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs bash">pip install gevent<br><span class="hljs-comment"># 重新启动</span><br>celery -A celeryAbout worker -l INFO -P gevent<br></code></pre></td></tr></table></figure>

<h2 id="admin后台管理"><a href="#admin后台管理" class="headerlink" title="admin后台管理"></a>admin后台管理</h2><ol>
<li>在admin后台 task results 可以查看到每一个任务的执行结果</li>
<li>在periodic tasks中可以新建，删除，停止 动态的更新定时任务</li>
<li>还可以配置定时执行周期</li>
</ol>
<h2 id="使用flower监控celery"><a href="#使用flower监控celery" class="headerlink" title="使用flower监控celery"></a>使用flower监控celery</h2><ol>
<li>安装<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cmake">pin <span class="hljs-keyword">install</span> flower<br></code></pre></td></tr></table></figure></li>
<li>启动 <figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs nginx"><span class="hljs-comment"># 默认在 5555端口</span><br><span class="hljs-attribute">celery</span> -A celeryAbout flower<br></code></pre></td></tr></table></figure>
浏览器访问：<br><a target="_blank" rel="noopener" href="http://127.0.0.1:5555/">http://127.0.0.1:5555/</a></li>
</ol>
<p>可以查看正在执行、成功、失败 的任务，也可以停止正在运行的任务</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>1.celery-django环境搭建</div>
      <div>https://sweetshance.github.io/2024/06/17/celery+django搭建学习/1-celery-django环境搭建/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>ShanCe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2024年6月17日</div>
        </div>
      
      
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2024/06/18/web%E7%9F%A5%E8%AF%86/vue%E4%BD%BF%E7%94%A8proxyTable%E5%8A%A0axios%E5%AE%9E%E7%8E%B0%E5%90%8E%E7%AB%AF%E5%9C%B0%E5%9D%80%E8%87%AA%E5%8A%A8%E6%8B%BC%E6%8E%A5/" title="vue使用proxyTable加axios实现后端地址自动拼接">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">vue使用proxyTable加axios实现后端地址自动拼接</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2024/06/14/celery+django%E6%90%AD%E5%BB%BA%E5%AD%A6%E4%B9%A0/celery-django%E6%8A%A5%E9%94%99/" title="celery+django报错">
                        <span class="hidden-mobile">celery+django报错</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="http://82.157.172.231/" target="_blank" rel="nofollow noopener"><span>无聊</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>ShanCe</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
